package at.tuwien.seminar.scrum1.proxies;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import at.tuwien.seminar.scrum1.hibernate.HibernateUtil;
import at.tuwien.seminar.scrum1.model.Room;

public class RoomProxy {

	private static RoomProxy instance;
	private EntityManager em;

	private RoomProxy() {
		em = HibernateUtil.getEntityManagerFactory().createEntityManager();
	}

	public static RoomProxy getInstance() {
		return instance == null ? instance = new RoomProxy() : instance;
	}

	public List<Room> getAll() {
		return getAll(em);
	}
	
	
	public List<Room> getAll(EntityManager em) {
		return (List<Room>)em.createQuery("from Room").getResultList();
	}
	
	public long insertRoom(Room room)
	{
		return insertRoom(room,em);
	}
	
	public long insertRoom(Room room, EntityManager em)
	{
		em.getTransaction().begin();
		em.persist(room);
		em.getTransaction().commit();
		
		return room.getId();
	}
	
	public void deleteRoom(Room room) {
        deleteRoom(room,em);
    }

    public void deleteRoom(Room room, EntityManager em) {
        em.getTransaction().begin();
		em.remove(room);
		em.getTransaction().commit();
    }

	public Room updateRoom(Room room) {
        updateRoom(room,em);

        return room;
    }

    public Room updateRoom(Room room, EntityManager em) {
        em.getTransaction().begin();
		em.merge(room);
		em.getTransaction().commit();
		
		return room;
    }


    public Long extractId(String name) {
        return Long.parseLong(name.substring(name.indexOf("[") + 1, name.length() - 1));
    }

     public List<String> getFreeRooms(Date start, Date end) {
        List<? extends Room> result= em.createQuery("" +
    			"from Room where id not in (select room.id from Reservation " +
    			"WHERE ((:start BETWEEN startDate AND endDate) " +
    			"OR (:end BETWEEN startDate AND endDate)))")
    			.setParameter("start", start)
    			.setParameter("end",end).getResultList();

        List<String> choices = new ArrayList<String>();

        for (Room r : result) {
            choices.add(r.getName() + " [" + r.getId() + "]");
        }
        return choices;

    }

    public Room getById(Long id) {
        	List<Room> rooms= em.createQuery("from Room WHERE id=:id", Room.class).setParameter("id", id).getResultList();

		if(!rooms.isEmpty())
			return rooms.get(0);
		else
			return null;
    }


}
